<template>
    <div>
        <div class="container" style="margin-bottom: 20px;">
            <el-tag class="tag-header" :class="selectTag==1?'active':''" @click="selectClick(1)">历史数据</el-tag>
            <el-tag class="tag-header" :class="selectTag==2?'active':''" @click="selectClick(2)">日报表</el-tag>
            <el-tag class="tag-header" :class="selectTag==3?'active':''" @click="selectClick(3)">月报表</el-tag>
            <el-tag class="tag-header" :class="selectTag==4?'active':''" @click="selectClick(4)">年报表</el-tag>
            <el-tag class="tag-header" :class="selectTag==5?'active':''" @click="selectClick(5)">自定义</el-tag>
            <el-date-picker v-if="selectTag==5"
                    v-model="selfTime"
                    type="daterange"
                            :picker-options="pickerOptions" unlink-panels value-format="yyyy-MM-dd"
                            start-placeholder="开始日期"
                            @change="selfChangeTime"
                            end-placeholder="结束日期">
            </el-date-picker>
        </div>
    <div class="container">

        <div>
            <div class="inline-block" v-if="selectTag!=5">
                <div class="demonstration">统计时间：</div>
                <el-date-picker
                        v-model="statisticTime"
                        :type="pickerType"
                        :value-format="valFormat"
                        placeholder="选择日期">
                </el-date-picker>
            </div>
            <div class="inline-block" v-if="selectTag!=1">
                <div class="demonstration">能源类型：</div>
                <el-select v-model="energyType" placeholder="请选择">
                    <el-option v-for="item in energyData" :key="item.id" :label="item.name"
                    :value="parseInt(item.id)">
                    </el-option>
                </el-select>
            </div>
            <div class="inline-block">
                <div class="demonstration">统计设备：</div>
                <el-select v-model="value3" multiple placeholder="请选择" @change="removeTag($event)">
                    <el-option
                            v-for="item in checkSelectedData"
                            :key="item.deviceId"
                            :label="item.deviceName"
                            :value="item.deviceId">
                    </el-option>
                </el-select>
                <el-button type="primary" @click="dialogVisible=true">选择</el-button>
            </div>
            <div class="inline-block" v-if="selectTag==1">
                <div class="demonstration">数据类型：</div>
                <el-select v-model="selectedTypeData" placeholder="请选择">
                    <el-option
                            v-for="item in typeData"
                            :key="item.dataId"
                            :label="item.dataName"
                            :value="item.dataId">
                    </el-option>
                </el-select>
            </div>
            <div class="inline-block">
                <el-button type="primary" icon="el-icon-search" @click="searchBtn">搜索</el-button>
            </div>
        </div>
        <div>
            <div style="overflow: hidden;width: 100%;">
                <div id="table-chart1" v-if="selectTag==1" style="width:98.2%;height:500px;float:left;border:1px solid #ddd;marginTop:15px;padding:10px;"></div>
                <div id="table-chart3" v-else style="width:98.2%;height:500px;float:left;border:1px solid #ddd;marginTop:15px;padding:10px;"></div>
            </div>
            <div style="overflow: hidden;width: 100%;">
                <div v-if="selectTag==1">
                    <template>
                        <el-table stripe border :data="tableData" style="width: 100%;margin-top: 15px;">
                            <el-table-column prop="orderNO" label="序号"></el-table-column>
                            <el-table-column prop="date" label="时间" :formatter="formatTime"></el-table-column>
                            <el-table-column prop="data" label="表底读数"></el-table-column>
                        </el-table>
                    </template>
                </div>
                <div v-else>
                    <div id="table-chart2" style="width:98.2%; height:500px;float:right;border:1px solid #ddd;marginTop:15px;padding:10px;"></div>
                </div>
            </div>

        </div>
        <div>
            <el-dialog
                    title="选择设备"
                    :visible.sync="dialogVisible"
                    destroy-on-close
                    :close-on-click-modal="$modelGolbParam.closeOnClickModal"
                    :close-on-press-escape="$modelGolbParam.closeOnPressEscape"
                    @opened="openDialog"
                    width="80%">
                <div>
                    <v-selectdevice></v-selectdevice>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="selectedDeviceData">确 定</el-button>
                  </span>
            </el-dialog>
        </div>
    </div>
    </div>
</template>

<script>
    import {getBaseEnergyTypeListNews,getDeviceAndData,getDeviceHisData} from  '../../../api/index';
    import vSelectdevice from './selectDeviceMask.vue';
    import bus from '../../common/bus';
    import {famatDatesTimes} from '../../common/com';
    var all_this = null;
    export default {
        name: "energy-statistic-device",
        components:{
            vSelectdevice
        },
        data(){
            return {
                statisticTime:'',
                selfTime:'',
                valFormat:'yyyy-MM-dd',
                energyData:'',
                energyType:'',
                selectedTypeData:'',
                typeData:[],
                dialogVisible:false,
                value2:'',
                value3:[],
                selectTag:1,
                pickerType:'date',
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                    onPick(){
                        all_this.staticisType = 4;
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            all_this.staticisType = 1;
                            const end = new Date();
                            const start = new Date();
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            all_this.staticisType = 1;
                            start.setTime(start.getTime() - 3600 * 1000 * 24 );
                            end.setTime(end.getTime() - 3600 * 1000 * 24 );
                            picker.$emit('pick', [start, end]);

                        }
                    },{
                        text: '最近一周',
                        onClick(picker) {
                            all_this.staticisType = 4;
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            all_this.staticisType = 4;
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近两个月',
                        onClick(picker) {
                            all_this.staticisType = 4;
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 60);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },

                radioSelectedData:'',
                checkSelectedData:'',
                staticisType:0,
                tableData:[],
                chart1Data:{},
                chart3Data:{},
            }
        },
        created(){
            all_this = this;
            bus.$on('markSelectedData',(val)=>{
                this.radioSelectedData = val;
            })
            bus.$on('markSelectedMoreData',(val)=>{
                // console.log(val)
                this.checkSelectedData = val;
            })
            this.getEnergyTypeData();

        },
        beforeDestroy(){
            bus.$off("selectedEneryTypeVal")
            bus.$off("selectTagStr")
        },
        methods:{
            getDeviceHisData(){
                getDeviceHisData({
                    dataId:this.selectedTypeData,
                    energyType:this.selectTag == 1 ? "" : this.energyType,
                    deviceId:this.selectTag == 1 ? this.radioSelectedData.deviceId : '',
                    deviceIds:this.selectTag == 1 ? [] : this.value3,
                    staticisType:this.staticisType,
                    startDate:this.selectTag==5?this.selfTime[0]:this.statisticTime,
                    endDate:this.selectTag==5?this.selfTime[1]:'',
                }).then((res)=>{
                    this.tableData = res.dataTable;
                    this.chart1Data['x'] = res.dataX;
                    this.chart1Data['y'] = res.dataY;
                    //如果是多项数据项
                    if(res.count){
                        this.chart3Data['y'] = [];
                        this.chart3Data['x'] = res.dataX;
                        for(var i=0;i<res.count;i++){
                            var str = 'dataY'+i;
                            this.chart3Data['y'].push(res[str])
                        }
                        this.eharts3Init();
                        this.chart2Data = res.BarY;
                        this.eharts2Init()
                    }else{
                        this.eharts1Init();
                    }

                })
            },
            removeTag(val,index){
                console.log(val)
                console.log(index)
            },
            getEnergyTypeData(){
                getBaseEnergyTypeListNews({}).then((res)=>{
                    this.energyData = res
                })
            },
            getDeviceAndData(){
                getDeviceAndData({
                    deviceId:this.radioSelectedData.deviceId
                }).then((res)=>{
                    this.typeData = res;
                })
            },
            selfChangeTime(val){
                var stepTime = 60*24*60*60*1000;
                if(new Date(val[1]).getTime() - new Date(val[0]).getTime() > stepTime){
                    this.$message.error('时间范围在两个月之内');
                }
            },
            formatTime(row, column, cellValue){
                return famatDatesTimes(cellValue);
            },
            openDialog(){
                bus.$emit('selectTagStr',this.selectTag);
                bus.$emit('selectedEneryTypeVal',this.energyType)
            },
            selectClick(v){
                this.selectTag = v;
                this.value3 = [];
                if(v == 1){
                    this.pickerType = "date"
                    this.staticisType = 0;
                }
                if(v == 2){
                    this.pickerType = "date"
                    this.valFormat = 'yyyy-MM-dd';
                    this.staticisType = 1;
                }
                if(v == 3){
                    this.pickerType = "month"
                    this.valFormat = 'yyyy-MM';
                    this.staticisType = 2;
                }
                if(v == 4){
                    this.pickerType = "year"
                    this.valFormat = 'yyyy';
                    this.staticisType = 3;
                }
                if(v==5){
                    this.staticisType = 4;
                }
            },
            selectedDeviceData(){
                this.value3 = [];
                if(this.selectTag==1){
                    this.value3 = [this.radioSelectedData.deviceName];
                    this.getDeviceAndData();
                }else{
                    for(var i=0;i<this.checkSelectedData.length;i++){
                        this.value3.push(this.checkSelectedData[i].deviceId)
                        // this.value3.push(this.checkSelectedData[i].deviceName)
                    }
                    // console.log(this.value3)
                }
                this.selectedTypeData = ''
                this.dialogVisible = false;

            },
            searchBtn(){
                // console.log(this.selectTag==5?this.selfTime:this.statisticTime)
                // console.log(this.radioSelectedData.deviceId)
                // console.log(this.selectedTypeData)
                // console.log(this.value3)
                // console.log(this.checkSelectedData)
                if(this.value3.length<1){
                    this.$message.error('请选择统计设备')
                    return ;
                }
                this.getDeviceHisData()
            },
            eharts1Init() {
                var $_this1 = this;
                // document.getElementById('table-chart1').innerHTML = '';
                // 基于准备好的dom，初始化echarts实例
                var myChart1 = this.$echarts.init(document.getElementById('table-chart1'));

                // 绘制图表
                var option1 = {
                    title: {
                        text: $_this1.chart1Data.x.title,//'用电量和用水量',
                        sub:$_this1.chart1Data.x.secondTitle
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        // data: lengData//['用电量', '用水量']
                    },
                    toolbox: {
                        show: true,
                        orient: 'vertical',
                        top: 'middle',
                        feature: {
                            dataView: {show: true, readOnly: false},
                            magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                            restore: {show: true},
                            saveAsImage: {show: true}
                        }
                    },
                    calculable: true,
                    xAxis: [
                        {
                            type: 'category',
                            data:  $_this1.chart1Data.x.data2//['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            axisLabel:{
                                formatter:function(val,index){
                                    return val +' '+$_this1.chart1Data.x.unit;
                                }
                            }
                        }
                    ],
                    dataZoom: [{show: true, start: 0, end: 100},{type: 'inside', start: 0, end: 100}],
                    series: [
                        {
                            // name: $_this1.chart1Data.y[i].txt,//'用电量',
                            type: 'bar',
                            data: $_this1.chart1Data.y.data,//[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                            markPoint: {
                                data: [{type: 'max', name: '最大值'},{type: 'min', name: '最小值'}]
                            },
                            markLine: {
                                data: [{type: 'average', name: '平均值'}]
                            }
                        }
                    ],
                };
                myChart1.clear();
                myChart1.setOption(option1);
            },
            eharts2Init() {
                var myChart2 = this.$echarts.init(document.getElementById('table-chart2'))
                var $_this2 = this;
                var lengData = [];
                for(var i=0;i<$_this2.chart2Data.length;i++){
                    lengData.push($_this2.chart2Data[i].name);
                }
                var option2 = {
                    title: {
                        text: $_this2.chart1Data.x.title,//new Date().getFullYear()+'标煤比例分析',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        data: lengData//['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
                    },
                    toolbox: {
                        show: true,
                        orient: 'vertical',
                        top: 'middle',
                        feature: {
                            dataView: {show: true, readOnly: false},
                            magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                            restore: {show: true},
                            saveAsImage: {show: true}
                        }
                    },
                    series: [
                        {
                            name: '占比',
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: $_this2.chart2Data,
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                myChart2.clear();
                myChart2.setOption(option2);
            },
            eharts3Init() {
                var $_this1 = this;
                // document.getElementById('table-chart1').innerHTML = '';
                // 基于准备好的dom，初始化echarts实例
                var myChart1 = this.$echarts.init(document.getElementById('table-chart3'));
                var dataV = [],lengData = [];
                console.log( $_this1.chart3Data)
                for(var i=0;i<$_this1.chart3Data.y.length;i++){
                    lengData.push($_this1.chart3Data.y[i].txt)
                    var valY = {
                        name: $_this1.chart3Data.y[i].txt,//'用电量',
                        type: 'bar',
                        data: $_this1.chart3Data.y[i].data,//[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                        markPoint: {
                            data: [{type: 'max', name: '最大值'},{type: 'min', name: '最小值'}]
                        },
                        markLine: {
                            data: [{type: 'average', name: '平均值'}]
                        }
                    }
                    dataV.push(valY)
                }
                // 绘制图表
                var option1 = {
                    title: {
                        text: $_this1.chart3Data.x.title,//'用电量和用水量',
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: lengData//['用电量', '用水量']
                    },
                    toolbox: {
                        show: true,
                        orient: 'vertical',
                        top: 'middle',
                        feature: {
                            dataView: {show: true, readOnly: false},
                            magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                            restore: {show: true},
                            saveAsImage: {show: true}
                        }
                    },
                    calculable: true,
                    xAxis: [
                        {
                            type: 'category',
                            data:  $_this1.chart3Data.x.data2//['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            axisLabel:{
                                formatter:function(val,index){
                                    return val +' '+$_this1.chart3Data.y[0].unit;
                                }
                            }
                        }
                    ],
                    dataZoom: [{show: true, start: 0, end: 100},{type: 'inside', start: 0, end: 100}],
                    series: dataV,
                };
                myChart1.clear();
                myChart1.setOption(option1);
            },
        },
    }
</script>

<style scoped>
    /deep/ .el-tag{
        margin-right: 25px;
        line-height: 36px;
        height: 36px;
        font-size: 16px;
        background-color: #fff;
        border: 0;
        cursor: pointer;
    }
    .inline-block{
        display: inline-block;
        margin-right: 20px;
    }
    .inline-block .demonstration{
        margin-bottom: 10px;
        font-size: 14px;
    }
    .tag-header{
        color: #0FBBB5;
    }
    .tag-header.active{
        color: #fff;
        background-color: #0fbbb5;
    }
    /deep/ .inline-block .el-tag {
          margin-right: 0;
         line-height: 20px;
         height: 20px;
        font-size: 12px;
    }
</style>